import React, { PureComponent } from 'react'
import { Button, Form, message } from 'antd'
import Tools from '@/utils/Tools'
import { DataDevLogger } from '@/components'
import styles from './index.less'
import { dataqualitystop, runRule, taskLog } from '../api'

const Bus = Tools.Bus

export default class DataQualityDetail extends PureComponent {
  constructor(props) {
    super(props)
    this.state = {
      loggerList: [],
      activeKey: '0',
      runState: 0,
      resultss: [
        {
          result: '运行日志',
          value: ['暂无运行'],
          key: 'logger',
          name: '运行日志',
        },
      ],
    }
  }

  componentDidMount() {
  }

  /**
   * 获取内置模板的规则
   */
  modelRule = (data) => {
    data.ruleConditions && data.ruleCondition
      ? data.ruleConditions.map((obj) => {
        obj.items
          && obj.items.map((o, k) => {
            o.value = JSON.parse(data.ruleCondition)[k].value
          })
      })
      : null
    data.ruleCondition
      && JSON.parse(data.ruleCondition).map((obj) => {
        if (obj.key === 'date') {
          data[obj.key] = obj.value
        } else {
          data[obj.key] = obj.value
        }
      })
    return (
      <div>
        <Form.Item
          label="规则类型"
        >
          <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.ruleType ? '表级规则' : '字段级规则'}</div>
        </Form.Item>

        <Form.Item
          label="规则模板"
        >

          <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.templateName}>{data && data.templateName}</div>
        </Form.Item>
        {data
          && data.ruleConditions
          && data.ruleConditions.length
          && data.ruleConditions[0]
          && data.ruleConditions[0].items
          && data.ruleConditions[0].items.length > 1
          ? (
            <Form.Item
              label={data.ruleConditions[0].name}
            >
              <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && `${data.min}~${data.max}`}</div>
            </Form.Item>
          )
          : data
          && data.ruleConditions
          && data.ruleConditions[0]
          && data.ruleConditions[0].items
          && data.ruleConditions[0].items.map(
            (obj, k) => (
              <div key={k}>
                <Form.Item
                  label={data.ruleConditions[0].name}
                >
                  {{
                    number: <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data[obj.key]}</div>,
                    text: <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data[obj.key]}</div>,
                    date: <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data[obj.key]}</div>,
                  }[obj.dataType]}
                </Form.Item>
              </div>
            ),
          )}
        {data && data.compareTypes && (
          <Form.Item
            label="比较方式"
          >
            <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.ruleCompareTypeName}</div>
          </Form.Item>
        )}
        {data && data.expectValue && (
          <Form.Item
            label="期望值"
          ><div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.ruleExpectValue}</div>
          </Form.Item>
        )}
      </div>
    )
  };

  /**
   * 获取自定义模板的规则
   */
  customRule = (data) => (
    <div>
      <Form.Item
        label="SQL"
      >
        <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.diySql}</div>
      </Form.Item>
      <Form.Item
        label="比较方式"
      >
        <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data && ['大于', '大于等于', '等于', '小于', '小于等于', '不等于', '属于', '不属于'][data.ruleCompareType]}</div>
      </Form.Item>
      <Form.Item
        label="期望值"
      ><div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.ruleExpectValue}</div>
      </Form.Item>
    </div>
  );

  // 任务开始
  startFlowTask = () => {
    if (this.state.runState === 1) return
    const { taskNode } = this.props
    runRule({
      nodeId: taskNode.id,
    }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        this.setState({
          jobId: res.data,
          runState: 1,
        })
        Bus.emit('iconUpFn', this.props.taskNode.id)
        this.taskLog(res.data)
      } else {
        message.error(res.msg)
      }
    })
  }

  // 任务日志
  taskLog = (jobId, offset) => {
    taskLog({
      jobId,
      offset: offset || offset === 0 ? offset : 0,
    }).then((res) => {
      if (res.status === 200) {
        clearTimeout(this.time)
        const { logContent, logEnd, results } = res.data
        const { resultss } = this.state

        let { loggerList } = this.state
        if (logContent && logContent.length) {
          loggerList = loggerList.concat(logContent)
        }
        resultss[0].value = loggerList || []

        const arr = this.state.resultss
        let newResults = [...results]

        if (newResults && newResults.length) {
          newResults.map((obj) => {
            obj.jobId = jobId
          })
          newResults = arr.concat(newResults)
        }

        newResults && newResults.length
          ? newResults.map((item, k) => {
            item.name ? null : (item.name = `结果[${k}]`)
          })
          : null
        this.setState({
          loggerList,
          resultss: newResults && newResults.length ? newResults : arr,
        }, () => {
          this.time = setTimeout(() => {
            this.taskLog(jobId, res.data.offset)
          }, 2000)
        })
        if (logEnd) {
          clearTimeout(this.time)
          this.setState({
            runState: 0,
          })
        }
      } else {
        clearTimeout(this.time)
        this.setState({
          runState: 0,
        })
        message.error(res.msg)
      }
    })
  }

  // 结束任务
  stopTask = () => {
    if (this.state.runState === 0) return
    const { jobId } = this.state
    dataqualitystop({ jobId }).then((res) => {
      if (res.status === 200) {
        message.success(res.msg)
        clearTimeout(this.time)
        this.setState({
          runState: 0,
        })
      } else {
        message.error(res.msg)
      }
    })
  }

  render() {
    const {
      loggerList, resultss, runState,
    } = this.state
    const { data, taskNode } = this.props
    return (
      <div className={`${styles.page_content} ${styles.page_content_off}`}>
        <div className={styles.back_bar}>
          <dl
            onClick={() => {
              this.startFlowTask()
            }}
            className={`${runState === 1 && styles.disable}`}
          >
            <dt><i className="iconfont icon-yunhang" /></dt>
            <dd>运行</dd>
          </dl>
          <dl
            onClick={() => {
              this.stopTask()
            }}
            className={`${runState === 0 && styles.disable}`}
          >
            <dt><i className="iconfont icon-tingzhi" /></dt>
            <dd>停止</dd>
          </dl>
          <Button onClick={() => {
            this.props.createChange()
          }}
          >编辑
          </Button>
        </div>
        <div className={styles.page_content_off_content}>
          <Form
            className={styles.form}
            colon={false}
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 20 }}
          >
            <Form.Item
              label="数据表"
            >
              <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.tblName}>{data && data.tblName}</div>
            </Form.Item>
            {data && data.ruleDiy == 0 ? (
              <Form.Item
                label="规则字段"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.fieldNames}>
                  {data && data.fieldNames}
                  {/* {data && data.fieldNames && data.fieldNames.split(',').map((value) => <span className={styles.text_overflow_single_span}>{value}</span>)} */}
                </div>
              </Form.Item>
            ) : null}
            {data && data.partitionExpression ? (
              <Form.Item
                label="分区表达式"
              >
                <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.partitionExpression}>{data && data.partitionExpression}</div>
              </Form.Item>
            ) : null}
            {/* <Form.Item
              label="强弱"
            >
              <div className={`${styles.form_item} ${styles.text_overflow_single}`}>{data && data.ruleStrength ? '强' : '弱'}</div>
            </Form.Item> */}
            <Form.Item
              label="规则"
            >
              <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.ruleDiy}>{data && data.ruleDiy == 1 ? '自定义规则' : '模板规则'}</div>
            </Form.Item>
            {(data && data.ruleDiy || data && data.ruleDiy == 0) && {
              0: this.modelRule(data),
              1: this.customRule(data),
            }[data.ruleDiy]}
            <Form.Item
              label="描述"
            >
              <div className={`${styles.form_item} ${styles.text_overflow_single}`} title={data && data.remark}>{data && data.remark}</div>
            </Form.Item>
          </Form>
        </div>
        <DataDevLogger
          list={loggerList || []}
          jobId={this.state.jobId}
          className={styles.flow_log}
          style="flow"
          results={resultss}
          activeKey={this.state.activeKey}
          taskId={taskNode.id}
        />
      </div>
    )
  }
}
